package com.mj.beian.service;

import java.util.Map;
import java.util.Random;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.mj.beian.util.HttpUtils;
/**
 * 网站备案查询
 * @author zhaominglei
 * @date 2015-3-27
 * 
 */
public class BeianService extends BaseService {
	@SuppressWarnings("unused")
	private static final String TAG = BeianService.class.getSimpleName();
	private static final String GETVERIFYCODE_URL = "http://www.miitbeian.gov.cn/getVerifyCode"; //miitbeian
	private static final String VALIDCODE_URL = "http://www.miitbeian.gov.cn/common/validate/validCode.action"; //miitbeian
	private static final String BEIANSEARCH_URL = "http://www.miitbeian.gov.cn/icp/publish/query/icpMemoInfo_searchExecute.action"; //miitbeian
	private static final String[] beianTitles = new String[]{"主办单位名称", "主办单位性质", "网站备案/许可证号", "网站名称", "网站首页网址", "审核时间"};
	private static final String separator = ": ";
	
	public Map<String, Object> getVerifyCode() {
		Map<String, Object> result = HttpUtils.getVerifyCode_Miitbeian(GETVERIFYCODE_URL+"?"+new Random().nextInt(100));
		return result;
	}
	
	public boolean validCode(String cookie, String verifycode) {
		if (cookie == null || cookie.equals("") 
				|| verifycode == null || verifycode.equals("")) {
			return false;
		}
		String html = HttpUtils.validCode_Miitbeian(cookie, VALIDCODE_URL, "validateValue="+verifycode, null);
		if (html != null && html.equals("{\"result\":true}")) {
			return true;
		} else {
			return false;
		}
	}
	
	public String beianSearch(String cookie, String verifycode, String domainname) {
		domainname = domainname.replaceAll("http://", "").replaceAll("www.", "").replaceAll("www", "");
		if (cookie == null || cookie.equals("") 
				|| verifycode == null || verifycode.equals("")
				|| domainname == null || domainname.equals("")) {
			return null;
		}
		String param = "siteName=&condition=1&siteDomain="+domainname+"&siteUrl=&mainLicense=&siteIp=&unitName=&mainUnitNature=-1&certType=-1&mainUnitCertNo=&verifyCode="+verifycode;
		String html = HttpUtils.beianSearch_Miitbeian(cookie, BEIANSEARCH_URL, param, "GBK");
		if (html != null && !html.equals("")) {
			StringBuilder result = new StringBuilder();
			Document document = Jsoup.parse(html);
			Elements elements = document.getElementsByAttributeValue("class", "bxy");
			int i = 0;
			for (Element element : elements) {
				result.append(beianTitles[i]).append(separator).append(element.text()).append("\n\n");
				i++;
			}
			return result.toString();
		}
		return null;
	}
}
